import datetime
import json
import logging

from django.http import JsonResponse
from django.shortcuts import render
from wxcloudrun.models import dailyReport
from wxcloudrun.models import dailyReport2
from wxcloudrun.models import EmpTestNo
from django.db.models import Avg, Count, Sum

logger = logging.getLogger('log')

def adddailyReport2(body):
    for i in body:
        b = dailyReport2()
        line = body[i]
        print(line)
        for k in list(line.keys()):
            setattr(b, k,line[k])
        b.save()




def index(request, _):
    """
    获取主页

     `` request `` 请求对象
    """

    return render(request, 'index.html')


def counter(request, _):
    """
    获取当前计数

     `` request `` 请求对象
    """
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'GET' or request.method == 'get':
        rsp = get_count(request)
    elif request.method == 'POST' or request.method == 'post':
        rsp = update_count(request)
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                            json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))
    return rsp



def Serialization(objects) :
    '''
    _obj: objext -> list, Python 3.6新加入的特性, 用来标识这个方法接收一个对象并返回一个list
    orm.raw序列化
    '''
    _list = []
    _get = []
    for i in objects:
        _list.append(i.__dict__)

    for i in _list:
        del i['_state']
        _get.append(i)
    return _get

def get_count(request):
    try:
        data=dailyReport.objects.raw('select id,sj,dept_code,dept_name,sl,ry,cy from dailyReport')
        data=Serialization(data)
        return JsonResponse({'code': 0, 'data': data},
                                 json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'code': -1, 'data':str(e)},
                            json_dumps_params={'ensure_ascii': False})

    # try:
    #     body=request.body
    #     body = json.loads(str(body, 'utf-8'))
    #     print(body)
    #     data=dailyReport.objects.raw('select id,sj,dept_code,dept_name,sl,ry,cy from dailyReport where sj=\''+body['time']+'\'')
    #     data=Serialization(data)
    #     print(data)
    #     return JsonResponse({'code': 0, 'data': data},
    #                          json_dumps_params={'ensure_ascii': False})
    # except Exception as e:
    #     return JsonResponse({'code': -1, 'data': str(e)},
                       # json_dumps_params={'ensure_ascii': False})

def co(data):
    """ 输出格式标准化"""
    redata={}
    if len(data)>0:
        tempTime = data[0]['sj']
        redata[str(tempTime)]=[]
        for i in data:
            if i['sj']==tempTime:
                redata[str(tempTime)].append(i)
            else:
                tempTime=i['sj']
                redata[str(tempTime)] = []
                redata[str(tempTime)].append(i)
    return redata

def addTestNo(body):
    for i in body:
        b =EmpTestNo()
        line = body[i]
        b.name = line['name']
        b.phone = line['phone']
        b.testno = line['testno']
        b.date = line['date']
        b.save()

def searchTestNo(body):
    print(body)
    name=body['name']
    phone=body['phone']
    data = EmpTestNo.objects.values('date', 'testno').filter(
        name=name,phone=phone).order_by('-date')[0]

    return data
def update_count(request):

    body= request.body
    body= json.loads(str(body,'utf-8'))
    if 'add' in body:
        try:
            body=body['add']
            for i in body:
                b = dailyReport()
                line=body[i]
                b.sj=line['sj']
                b.dept_code=line['deptcode']
                b.dept_name=line['dn']
                b.sl=line['sl']
                b.cy=line['cy']
                b.ry=line['ry']
                b.save()
        except Exception as e:
            return (JsonResponse({'code': -1, "data": str(e)} ,json_dumps_params={'ensure_ascii': False}))
    elif 'searchRecord' in body:
        try:
            body = request.body
            body = json.loads(str(body, 'utf-8'))['searchRecord']
            time1 = body['timestart']
            time2 = body['timeend']
            data = dailyReport.objects.values('sj','dept_code', 'dept_name','sl','cy','ry').filter(sj__range=(time1, time2)).order_by('sj','dept_code')
            data = list(data)
            data=co(data)
            data1 = dailyReport2.objects.all().values().filter(date__range=(time1, time2)).order_by('date')

            return JsonResponse({'code': 0, 'data': data, 'data1': list(data1)},
                                json_dumps_params={'ensure_ascii': False})
        except Exception as e:
            return JsonResponse({'code': -1, 'data': str(e)},
                                json_dumps_params={'ensure_ascii': False})
    elif 'update' in body:
        body = body['update']
        try:
            adddailyReport2(body)

        except Exception as e:
            return JsonResponse({'code': -1, 'data': str(e)},
                                json_dumps_params={'ensure_ascii': False})

    elif 'addTestNo' in body:
        body=body['addTestNo' ]
        try:
            addTestNo(body)
        except Exception as e:
            return JsonResponse({'code': -1, 'data': str(e)},
                                json_dumps_params={'ensure_ascii': False})
    elif 'searchTestNo' in body:
        body=body['searchTestNo']
        try:
            data=searchTestNo(body)
            return JsonResponse({'code': 0, 'data': data, },
                                json_dumps_params={'ensure_ascii': False})
        except Exception as e:
            return JsonResponse({'code': -1, 'data': str(e)},
                                json_dumps_params={'ensure_ascii': False})


    else:
        return (JsonResponse({'code': -1, "data": 'error request function'}, json_dumps_params={'ensure_ascii': False}))
    return (JsonResponse({'code': 0, "data": body} ,json_dumps_params={'ensure_ascii': False}))

